export default class ContextMenu {
  private menuId: string;

  private menu: HTMLUListElement;

  private root: HTMLElement;

  constructor(menuId = 'my-context-menu', rootId = 'app') {
    this.menuId = menuId;
    this.menu = document.createElement('ul');
    this.menu.id = this.menuId;
    this.close();
    this.root = document.getElementById('app') as HTMLElement;
    this.root?.addEventListener('click', () => {
      this.close();
    });
    this.root?.addEventListener('contextmenu', () => {
      this.close();
    });
  }

  public show(x: number, y: number) {
    setTimeout(() => {
      this.menu.style.cssText = `left: ${x}px; top: ${y}px;`;
      this.root?.insertBefore(this.menu, this.root.firstChild);
    }, 10);
  }

  public addItem(name: string, callback: () => void) {
    const item = document.createElement('li');
    item.innerText = name;
    item.addEventListener('click', (event: MouseEvent) => {
      event.stopPropagation();
      this.close();
      callback();
    });
    this.menu.appendChild(item);
  }

  public close() {
    if (this.menu) {
      this.menu.remove();
    }
    const old = document.getElementById(this.menuId);
    if (old) {
      old.remove();
    }
  }
}
